package com.xixilala.ig

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ImageView
import android.widget.Toast
import kotlin.collections.ArrayList
import kotlin.math.abs

/***
 *  拼图
 *
 */
private const val BLANK_COLOR = Color.LTGRAY
private val grayBitmap = Bitmap.createBitmap(1,1,Bitmap.Config.RGB_565).apply { eraseColor(BLANK_COLOR) }

class GameImage : android.view.ViewGroup {

    /** ?X? 的拼图 **/
    private val size = 3
    /** 重置时，模拟触摸几步 **/
    private val complex = 100
    /** 完成后?秒后重置**/
    private val delayTimeReset:Long = 1000 * 1

    private var canTouch = true

    private var srcImage: Bitmap? = null
    private var grayPosition: Position? = null
    private var grayIndex: Int = 0

    private val totalIndex = size*size
    private val childList = ArrayList<IGImageView>(totalIndex)
    private val rightImages = ArrayList<Bitmap>(totalIndex)
    private val nowImages = ArrayList<Bitmap>(totalIndex)


    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    /****
     * 重置期间是不能点击的，把事件拦截了
     */
    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return !canTouch
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {

        val childCount = childCount
        val width = width / size
        val height = height / size

        if (childCount > 0) {

            for (index in 0..childCount) {
                val childView = getChildAt(index)
                val realIndex = index % size
                val cl = l + width * realIndex
                val ct = t + height * (index / size)
                val cr = l + width * (realIndex + 1)
                val cb = t + height * (index / size + 1)

                childView?.layout(cl, ct, cr, cb)
            }
        }
    }

    fun setImage(imageRes: Int) {

        post {
            val bmOption = BitmapFactory.Options().apply { }

            val viewWidth = width
            val viewHeight = height

            val bm = BitmapFactory.decodeResource(resources, imageRes, bmOption)
            srcImage = Bitmap.createScaledBitmap(bm, viewWidth, viewHeight, true)
        }
    }

    fun splitImage() {
        post {

            val viewWidth = width
            val viewHeight = height

            val childWidth = viewWidth / size
            val childHeight = viewHeight / size


            srcImage?.let { srcBitmap ->

                IGLog.d("init split image")
                canTouch = false
                removeAllViews()
                childList.clear()
                rightImages.clear()
                nowImages.clear()
                grayPosition = null
                grayIndex = 0

                // 创建所有小图
                for (vIndex in 0 until size) {

                    for (hIndex in 0 until size) {

                        val child = Bitmap.createBitmap(
                            srcBitmap, childWidth * hIndex,
                            childHeight * vIndex, childWidth, childHeight
                        )
                        val ivChild = IGImageView(context)

                        ivChild.scaleType = ImageView.ScaleType.FIT_XY
                        ivChild.layoutParams = LayoutParams(childWidth, childHeight)

                        if (vIndex == size - 1 && hIndex == size - 1) {
                            ivChild.setImageBitmap(grayBitmap)
                            rightImages.add(grayBitmap)
                        } else {
                            ivChild.setImageBitmap(child)
                            rightImages.add(child)
                        }
                        ivChild.position = Position(vIndex, hIndex)
                        childList.add(ivChild)
                    }
                }

                nowImages.addAll(rightImages)

                grayIndex = size * size - 1
                grayPosition = childList[grayIndex].position

                for (index in childList.indices) {
                    val item = childList[index]
                    addView(item)

                    item.setOnClickListener { i ->

                        val clickItem = i as IGImageView
                        grayPosition?.let {
                            if (clickItem.position.isAside(it)) {

                                val gray = childList[grayIndex]

                                val clickPositionBitmap = nowImages[index]
                                nowImages[index] = grayBitmap
                                nowImages[grayIndex] = clickPositionBitmap

                                clickItem.toggleView(gray)
                                grayPosition = clickItem.position

                                grayIndex = index
                            }
                        }


                        if (canTouch) {
                            checkRight()
                        }

                    }
                }

                fun randomOrder() {
                    for (clickItem in 0..complex) {
                        val x = grayPosition!!.xp
                        val y = grayPosition!!.yp

                        val newX: Int
                        val newY: Int

                        // 是否X座标保持不变
                        if (RmUtil.randomIsOddNum()) {

                            newX = x
                            //上还是下
                            if (RmUtil.randomIsOddNum()) {
                                newY = y - 1
                                if (-1 >= newY || newY >= size) {
                                    continue
                                }
                            } else {
                                newY = y + 1
                                if (-1 >= newY || newY >= size) {
                                    continue
                                }
                            }
                        } else {
                            newY = y
                            if (RmUtil.randomIsOddNum()) {
                                newX = x - 1
                                if (-1 >= newX || newX >= size) {
                                    continue
                                }
                            } else {
                                newX = x + 1
                                if (-1 >= newX || newX >= size) {
                                    continue
                                }
                            }
                        }
                        val index = newX * size + newY
                        childList[index].performClick()
                    }
                }


                postDelayed({
                    randomOrder()
                    canTouch = true
                }, 100)
            }
        }

    }

    /***
     * 检查是否拼好了
     */
    private fun checkRight() {
        var isSame = true
        for (position in rightImages.indices) {
            if (rightImages[position] != nowImages[position]) {
                isSame = false
                break
            }
        }

        if (isSame) {
            canTouch = false
            postDelayed({
                splitImage()
                canTouch = true
            }, delayTimeReset)
            Toast.makeText(context.applicationContext, "已完成！！！5秒后重置", Toast.LENGTH_SHORT).show()
        }
    }


    class Position(var xp: Int, var yp: Int) {

        fun isAside(grayPart: Position): Boolean {
            return when {
                grayPart.xp == xp -> {
                    abs((grayPart.yp - yp)) == 1
                }
                grayPart.yp == yp -> {
                    abs((grayPart.xp - xp)) == 1
                }
                else -> {
                    false
                }
            }
        }
        override fun toString(): String {
            return "(xp=$xp, yp=$yp)"
        }
    }
}


class IGImageView(context: Context?) : androidx.appcompat.widget.AppCompatImageView(context) {

    lateinit var position: GameImage.Position

    fun toggleView(grayView: IGImageView) {

        grayView.setImageBitmap((drawable as BitmapDrawable).bitmap)
        setImageBitmap(grayBitmap)
    }

    override fun toString(): String {
        return "${(drawable as BitmapDrawable).bitmap.byteCount}"
    }

}